package pyrachnid.view.component;

import java.io.File;

import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.filechooser.FileSystemView;

/**
 * @author zygou
 *
 */

public class ScenarFileChooser extends JFileChooser {

	private static final long serialVersionUID = 1L;
	
	public ScenarFileChooser(){
		super();
		setCurrentDirectory(new File("./Scenarios"));
		setMultiSelectionEnabled(false);
		setAcceptAllFileFilterUsed(false);		
		addChoosableFileFilter(new ScenarFileFilter());
		setFileSystemView(FileSystemView.getFileSystemView());
	}
	
	@Override
	public void approveSelection(){
	    File f = getSelectedFile();
	    if(getDialogType() == SAVE_DIALOG){
	    	if(!f.getName().endsWith(".scenar") && f.getName().split("\\.").length > 1 ){
    			JOptionPane.showMessageDialog(this, "The file choosen must ends with the extension .scenar !\n", "Extension Error", JOptionPane.ERROR_MESSAGE);
    			return;
    		}
    		else if(f.getName().split("\\.").length==1)  {
    			setSelectedFile(new File(getSelectedFile().getAbsoluteFile()+".scenar"));
    		}
    		else if(f.getName().endsWith(".scenar") && f.getName().split("\\.")[0].equals("") && f.getName().split("\\.").length==2) {
    			JOptionPane.showMessageDialog(this, "The file choosen must ends with the extension .scenar !\n", "Extension Error", JOptionPane.ERROR_MESSAGE);
    			return;
    		}
	    	if(getSelectedFile().exists()){
		        int result = JOptionPane.showConfirmDialog(this,"This file already exists, overwrite it?","Existing file",JOptionPane.YES_NO_CANCEL_OPTION);
		        switch(result){
		            case JOptionPane.YES_OPTION:
		                super.approveSelection();
		                return;
		            case JOptionPane.NO_OPTION:
		                return;
		            case JOptionPane.CANCEL_OPTION:
		                cancelSelection();
		                return;
		        }
	        }
	    }
	    super.approveSelection();
	}
}
